<template>
  <div class="tour-content">
    <div class="tour-desc-content" :class="positionClass" :style="computedStyle" ref="contentRef">
      <div class="header">
        <div class="title">{{ title }}</div>
        <div class="step-indicator" v-if="totalSteps > 1">{{ currentStep }}/{{ totalSteps }}</div>
      </div>
      <div class="content-desc">{{ desc }}</div>
      <div class="btn-box">
        <van-button v-if="showSkip" plain size="mini" @click="$emit('skip')">
          跳过
        </van-button>
        <van-button v-if="currentStep > 1" plain size="mini" @click="$emit('prev')">
          上一步
        </van-button>
        <van-button type="primary" size="mini" @click="currentStep < totalSteps ? $emit('next') : $emit('finish')">
          {{ currentStep < totalSteps ? '下一步' : '完成' }} </van-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { defineProps, computed, defineEmits, watch, onMounted, onUnmounted, ref, nextTick } from 'vue';
import { Button as VanButton } from 'vant';

// 定义props
const props = defineProps({
  title: { type: String, default: '' },
  desc: { type: String, default: '' },
  pos: {
    type: Object,
    required: true,
    default: () => ({})
  },
  currentStep: { type: Number, default: 1 },
  totalSteps: { type: Number, default: 1 },
  showSkip: { type: Boolean, default: true },
  placementPriority: {
    type: Array,
    default: () => ['bottom', 'top', 'right', 'left']
  }
});

// 定义emits
const emit = defineEmits(['prev', 'next', 'finish', 'skip']);

// DOM引用
const contentRef = ref(null);
const positionClass = ref('');

// 统一的位置更新函数
const updatePosition = () => {
  if (!contentRef.value) return;
  positionClass.value = calculateBestPosition();
};

// 计算最佳位置
const calculateBestPosition = () => {
  if (!contentRef.value || !props.pos) return '';

  const contentEl = contentRef.value;
  const contentWidth = contentEl.offsetWidth;
  const contentHeight = contentEl.offsetHeight;
  const { x, y, width, height } = props.pos;
  const windowWidth = window.innerWidth;
  const windowHeight = window.innerHeight;
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
  const margin = 16;

  // 考虑滚动偏移量的目标元素位置
  const targetRect = {
    x: x + scrollLeft,
    y: y + scrollTop,
    width,
    height
  };

  // 检查每个优先级位置是否可用
  for (const placement of props.placementPriority) {
    switch (placement) {
      case 'top':
        if (targetRect.y - contentHeight - margin > 0) return 'top';
        break;
      case 'bottom':
        if (targetRect.y + targetRect.height + contentHeight + margin < windowHeight) return 'bottom';
        break;
      case 'left':
        if (targetRect.x - contentWidth - margin > 0) return 'left';
        break;
      case 'right':
        if (targetRect.x + targetRect.width + contentWidth + margin < windowWidth) return 'right';
        break;
    }
  }

  // 如果没有理想位置，返回第一个可用位置
  for (const placement of props.placementPriority) {
    switch (placement) {
      case 'top':
        if (targetRect.y > 0) return 'top';
        break;
      case 'bottom':
        if (targetRect.y + targetRect.height < windowHeight) return 'bottom';
        break;
      case 'left':
        if (targetRect.x > 0) return 'left';
        break;
      case 'right':
        if (targetRect.x + targetRect.width < windowWidth) return 'right';
        break;
    }
  }

  return props.placementPriority[0];
};

// 计算内容定位样式
const computedStyle = computed(() => {
  if (!positionClass.value || !contentRef.value) return {};

  const contentEl = contentRef.value;
  const contentWidth = contentEl.offsetWidth;
  const contentHeight = contentEl.offsetHeight;
  const { x, y, width, height } = props.pos;
  const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
  const arrowSize = 8;
  const margin = 16;
  const style = {};
  const arrowOffset = {};

  switch (positionClass.value) {
    case 'top':
      style.left = `${Math.max(margin, Math.min(x + width / 2 - contentWidth / 2, window.innerWidth - contentWidth - margin))}px`;
      style.top = `${y - contentHeight - arrowSize + scrollTop}px`;
      // 计算箭头偏移量（指向目标元素底部中心）
      arrowOffset['--arrow-offset'] = `${x + width / 2 - parseInt(style.left) + scrollLeft}px`;
      break;
    case 'bottom':
      style.left = `${Math.max(margin, Math.min(x + width / 2 - contentWidth / 2, window.innerWidth - contentWidth - margin))}px`;
      style.top = `${y + height + arrowSize + scrollTop}px`;
      // 计算箭头偏移量（指向目标元素顶部中心）
      arrowOffset['--arrow-offset'] = `${x + width / 2 - parseInt(style.left) + scrollLeft}px`;
      break;
    case 'left':
      style.top = `${Math.max(margin, Math.min(y + height / 2 - contentHeight / 2, window.innerHeight - contentHeight - margin))}px`;
      style.left = `${x - contentWidth - arrowSize + scrollLeft}px`;
      // 计算箭头偏移量（指向目标元素右侧中心）
      arrowOffset['--arrow-offset'] = `${y + height / 2 - parseInt(style.top) + scrollTop}px`;
      break;
    case 'right':
      style.top = `${Math.max(margin, Math.min(y + height / 2 - contentHeight / 2, window.innerHeight - contentHeight - margin))}px`;
      style.left = `${x + width + arrowSize + scrollLeft}px`;
      // 计算箭头偏移量（指向目标元素左侧中心）
      arrowOffset['--arrow-offset'] = `${y + height / 2 - parseInt(style.top) + scrollTop}px`;
      break;
    default:
      return {};
  }
  console.log('arrowOffset', arrowOffset)
  return {
    ...style,
    ...arrowOffset,
    transition: 'all 0.3s ease'
  };
});

// 窗口大小变化和滚动监听
const handleResize = () => {
  updatePosition();
};

// 监听属性变化
watch(() => props.pos, () => {
  nextTick(() => updatePosition());
}, { deep: true, immediate: true });

watch([() => props.title, () => props.desc], () => {
  nextTick(() => updatePosition());
});

// 组件生命周期
onMounted(() => {
  window.addEventListener('resize', handleResize);
  window.addEventListener('scroll', handleResize, true);
  nextTick(() => updatePosition());
});

onUnmounted(() => {
  window.removeEventListener('resize', handleResize);
  window.removeEventListener('scroll', handleResize, true);
});
</script>

<style lang="scss" scoped>
.tour-desc-content {
  position: absolute;
  min-width: 200px;
  max-width: 300px;
  z-index: 1001;
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15);
  pointer-events: auto;

  // 箭头样式 - 上方向（指向目标元素底部中心）
  &.top::after {
    content: '';
    position: absolute;
    bottom: -8px;
    left: var(--arrow-offset);
    transform: translateX(-50%);
    border-width: 8px 8px 0;
    border-style: solid;
    border-color: #fff transparent transparent;
    box-shadow: 0 4px 4px rgba(0, 0, 0, 0.1);
  }

  // 箭头样式 - 下方向（指向目标元素顶部中心）
  &.bottom::after {
    content: '';
    position: absolute;
    top: -8px;
    left: var(--arrow-offset);
    transform: translateX(-50%);
    border-width: 0 8px 8px;
    border-style: solid;
    border-color: transparent transparent #fff;
    box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  }

  // 箭头样式 - 左方向（指向目标元素右侧中心）
  &.left::after {
    content: '';
    position: absolute;
    right: -8px;
    top: var(--arrow-offset);
    transform: translateY(-50%);
    border-width: 8px 0 8px 8px;
    border-style: solid;
    border-color: transparent transparent transparent #fff;
    box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
  }

  // 箭头样式 - 右方向（指向目标元素左侧中心）
  &.right::after {
    content: '';
    position: absolute;
    left: -8px;
    top: var(--arrow-offset);
    transform: translateY(-50%);
    border-width: 8px 8px 8px 0;
    border-style: solid;
    border-color: transparent #fff transparent transparent;
    box-shadow: -2px 0 4px rgba(0, 0, 0, 0.1);
  }

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
  }

  .title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
  }

  .step-indicator {
    font-size: 12px;
    color: #999;
    background: #f5f5f5;
    padding: 2px 6px;
    border-radius: 10px;
  }

  .content-desc {
    font-size: 14px;
    color: #666;
    margin-bottom: 16px;
    line-height: 1.5;
  }

  .btn-box {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    gap: 8px;
  }
}
</style>